//
//  LTChangeMyPhoneNumberVC.m
//  Learn
//
//  Created by zyl_macbookpro on 2024/3/30.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "LTChangeMyPhoneNumberVC.h"
#import "LTMineAPIManager.h"
//#import "LoginHistoryAccountView.h"

@interface LTChangeMyPhoneNumberVC ()<UITextFieldDelegate ,UITableViewDelegate,UITableViewDataSource>

@property(nonatomic ,strong)UITableView *tableView;

@property(nonatomic ,strong)UIView *tableHeaderView;

@property(nonatomic ,strong)UIView *tableFootorView;

@property(nonatomic ,strong)UIButton *confirmButton;

@property(nonatomic ,strong)UITextField *accountTextFiled;

@property(nonatomic ,strong)UITextField *veriftyTextFiled;

@property(nonatomic ,strong)UITextField *phoneVeriftyFiled;

@property(nonatomic ,strong)WKWebView *captchaWeb;

@property(nonatomic ,strong)NSMutableURLRequest *captchaRequest;

@property(nonatomic ,copy)NSString *captcha_token;

@property (nonatomic, strong) UIButton *sendCodeBtn;

@property (nonatomic, strong) NSTimer *captchaTimer;

@property (nonatomic, assign) NSInteger captchaCountDownSeconds;

@end

@implementation LTChangeMyPhoneNumberVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = LTWhiteColor;
    [self.view addSubview:self.tableView];
    

    [BaseRequest checkoutNetWorkStatus:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN) {
            [self reloadWeb];
        }
    }];
   
    
}
#pragma mark -API
- (void)sendMsg
{
    NSDictionary *dic = @{@"mobile":self.accountTextFiled.text,@"event":@"changemobile"};
    [LTMineAPIManager sendSMSWithParam:dic result:^(NSDictionary * _Nonnull dic) {
        if ([dic[@"code"] intValue] != 1) {
            [SVProgressHUD showImage:nil status:dic[@"msg"]];
            return;
        }
        [self startTimer];
    }];
}
- (void)changePhoneNumber
{
    NSDictionary *dic = @{@"mobile":self.accountTextFiled.text,@"mobile_captcha":self.phoneVeriftyFiled.text,@"captcha":self.veriftyTextFiled.text,@"captcha_token":self.captcha_token};
    [LTMineAPIManager changePhoneNumberWithParam:dic result:^(NSDictionary * _Nonnull dic) {
        
        if (dic&&[dic[@"code"] doubleValue] == 1) {
            [self reloadWeb];
            [self.navigationController popToRootViewControllerAnimated:YES];
         }else{
             [SVProgressHUD showImage:nil status:dic[@"msg"]];
         }
       
    }];
}


#pragma mark -UITableViewDelegate,UITableViewDelegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell =nil;
    
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    [cell.contentView removeAllSubviews];
    if(indexPath.row == 0)
    {
        [cell.contentView addSubview:self.accountTextFiled];
    }else if (indexPath.row == 1)
    {
        [cell.contentView addSubview:self.veriftyTextFiled];
    }else{
        [cell.contentView addSubview:self.phoneVeriftyFiled];
    }
    
    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
        return 3;
        
  
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 61;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{


}



#pragma mark -UITextFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    //[[textField viewWithTag:1001] setBackgroundColor:kOrangeLineColor];
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    //[[textField viewWithTag:1001] setBackgroundColor:kLineColor];
    
    return  YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}
#pragma mark - private
- (void)startTimer
{
    self.sendCodeBtn.enabled = NO;
    [self.captchaTimer fire];
}

- (void)resetTimer
{
    if (self.captchaTimer) {
        self.captchaCountDownSeconds =60;
        [self.captchaTimer invalidate];
        self.captchaTimer =nil;
        
        self.sendCodeBtn.enabled =YES;
        [self.sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
}
-(void)oneMinutCutdown:(NSTimer *)aTimer
{
    self.captchaCountDownSeconds--;
    [self.sendCodeBtn setTitle:[NSString stringWithFormat:@"%ld秒重新发送",self.captchaCountDownSeconds] forState:UIControlStateNormal];
    
    //当计时器为0时，关闭计时器
    if (self.captchaCountDownSeconds ==0)
    {
        [self resetTimer];
    }
}
#pragma mark -event response

- (void)tapClick
{
    [self.view endEditing:YES];
}

- (void)confirmButtonAction
{
    [self.view endEditing:YES];
    NSString *str = @"";
    if (self.accountTextFiled.text.length == 0) {
        str = @"手机号不能为空！";
    }
    
    if (self.veriftyTextFiled.text.length == 0) {
        str = @"验证码不能为空！";
    }
    
    if (self.phoneVeriftyFiled.text.length == 0) {
        str = @"手机验证码不能为空！";
    }
    
    
    if (str.length == 0) {
        [MethodTool getCookieWithwebView:self.captchaWeb success:^(BOOL success) {
            [self changePhoneNumber];
        }];
    }else{
        [SVProgressHUD showImage:nil status:str];
    }
}

-(void)reloadWeb
{
    [self.view endEditing:YES];
    [self.captchaWeb loadRequest:self.captchaRequest];
}

-(void)textFieldResignTapAction:(UITapGestureRecognizer *)sender
{
    [self.view endEditing:YES];
}
-(void)textEnd:(UITextField *)textField
{
    [self.tableView reloadData];
}
-(void)textChanged:(UITextField *)textField
{
    
   
}
- (void)sendCodeBtnClick
{
   if(self.accountTextFiled.text.length == 0)
   {
       [SVProgressHUD showImage:nil status:@"请输入手机号！"];
   }
    [self sendMsg];
}
#pragma mark -getters and setters
-(UITableView *)tableView{
    if (!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LTTopBarHeight, LTScreenWidth, LTScreenHeight - LTTopBarHeight) style:UITableViewStylePlain];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        _tableView.bounces = NO;
        [_tableView setBackgroundColor:LTWhiteColor];
        [_tableView setSeparatorColor:LTClearColor];
        [_tableView setTableHeaderView:self.tableHeaderView];
        [_tableView setTableFooterView:self.tableFootorView];
    }
    
    return _tableView;
}

-(UIView *)tableHeaderView
{
    if (!_tableHeaderView)
    {
        
        _tableHeaderView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, LTScreenWidth,210)];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
            [_tableHeaderView addGestureRecognizer:tap];
    
        UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(32, 32, LTScreenWidth - 64, 28)];
        titleLabel.font = MFontWithSize(20);
        titleLabel.text = @"更换手机号";
        [titleLabel setTextAlignment:NSTextAlignmentLeft];
        titleLabel.textColor = LTTextBlack;
        
        UILabel * subLabel = [[UILabel alloc] initWithFrame:CGRectMake(32, titleLabel.bottom + 8, LTScreenWidth - 64, 18)];
        subLabel.font = RFontWithSize(13);
        subLabel.text = @"绑定后，可使用手机号登录或找回密码";
        [subLabel setTextAlignment:NSTextAlignmentLeft];
        subLabel.textColor = rgba(102, 102, 102, 1);
        [_tableHeaderView addSubview:titleLabel];
        [_tableHeaderView addSubview:subLabel];
        
        _tableHeaderView.height = subLabel.bottom + 18;
       
    }
    
    return _tableHeaderView;
}

-(UIView *)tableFootorView
{
    if (!_tableFootorView)
    {
        _tableFootorView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, LTScreenWidth - 20, 20)];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
        [_tableFootorView addGestureRecognizer:tap];
       
        [_tableFootorView addSubview:self.confirmButton];
    
        _tableFootorView.height = self.confirmButton.bottom;
    }
    
    return _tableFootorView;
}

-(UIButton *)confirmButton
{
    if (!_confirmButton)
    {
        _confirmButton = [UIButton new];
        _confirmButton.frame =CGRectMake(32, 40, LTScreenWidth - 64, 44);
       
        [_confirmButton setTitle:@"确 定" forState:UIControlStateNormal];
       // [_confirmButton setTitleColor:rgba(181, 181, 181, 1) forState:UIControlStateNormal];
        [_confirmButton setTitleColor:LTWhiteColor forState:UIControlStateNormal];
        [_confirmButton.titleLabel setFont:MFontWithSize(14)];
        [_confirmButton addTarget:self action:@selector(confirmButtonAction) forControlEvents:UIControlEventTouchUpInside];
        _confirmButton.backgroundColor = rgba(41, 121, 255, 1);
        _confirmButton.layer.cornerRadius = 22;
        _confirmButton.layer.shadowColor = rgba(41, 121, 255, 0.50).CGColor;
        _confirmButton.layer.shadowOffset = CGSizeMake(0,4);
        _confirmButton.layer.shadowOpacity = 1;
        _confirmButton.layer.shadowRadius = 6;
    }
    
    return _confirmButton;
}

-(UITextField *)veriftyTextFiled
{
    if (!_veriftyTextFiled)
    {
        _veriftyTextFiled =[[UITextField alloc] initWithFrame:CGRectMake(32, 6, LTScreenWidth - 64, 49)];
        _veriftyTextFiled.font = MFontWithSize(16);
        _veriftyTextFiled.textColor = rgba(51, 51, 51, 1);
        _veriftyTextFiled.clearButtonMode =UITextFieldViewModeWhileEditing;
        _veriftyTextFiled.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入验证码" attributes:@{NSFontAttributeName:MFontWithSize(16)}];
        _veriftyTextFiled.delegate =self;
       
        if (@available(iOS 11.0,*)) {
            _veriftyTextFiled.textContentType =UITextContentTypeUsername;
        }
        [_veriftyTextFiled setAllCornersWithCornerRadius:6];
        _veriftyTextFiled.backgroundColor = rgba(247, 248, 250, 1);
        [_veriftyTextFiled addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
        UIView *leftSpaceView = [[UIView alloc] init];
        leftSpaceView.frame = CGRectMake(0,0,15,49);
        leftSpaceView.backgroundColor = rgba(247, 248, 250, 1);
        
        _veriftyTextFiled.leftViewMode = UITextFieldViewModeAlways;
        _veriftyTextFiled.leftView = leftSpaceView;
        UIView *rightSpaceView = [[UIView alloc] init];
        rightSpaceView.frame = CGRectMake(0,0,100,49);
        rightSpaceView.backgroundColor =rgba(245, 245, 245, 1);
        [rightSpaceView addSubview:self.captchaWeb];
        [self reloadWeb];
        UIButton *relodBtn = [UIButton new];
        relodBtn.frame = CGRectMake(0,0,100,49);;
       
        [rightSpaceView addSubview:relodBtn];
        [relodBtn addTarget:self action:@selector(reloadWeb) forControlEvents:UIControlEventTouchUpInside];
        _veriftyTextFiled.rightViewMode = UITextFieldViewModeAlways;
        _veriftyTextFiled.rightView = rightSpaceView;
        
    }

    return _veriftyTextFiled;
}
- (WKWebView *)captchaWeb
{
    if(!_captchaWeb)
    {
        _captchaWeb = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, 100, 49)];
        
    }
    return _captchaWeb;
}
- (NSMutableURLRequest *)captchaRequest
{
    self.captcha_token =  [NSString stringWithFormat:@"%d",arc4random()];
    NSString *url = [NSString stringWithFormat:@"%@%@%@%@",BASE_URL,LOGIN_CAPTCHA_URL,@"?id=",self.captcha_token];
    return [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
}
-(UITextField *)accountTextFiled
{
    if (!_accountTextFiled)
    {
        _accountTextFiled =[[UITextField alloc] initWithFrame:CGRectMake(32, 6, LTScreenWidth - 64, 49)];
        _accountTextFiled.font = MFontWithSize(16);
        _accountTextFiled.textColor = LTTextBlack;
        _accountTextFiled.clearButtonMode =UITextFieldViewModeWhileEditing;
        _accountTextFiled.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入父母或自己的手机号码" attributes:@{NSFontAttributeName:MFontWithSize(16)}];
        _accountTextFiled.delegate =self;
       // [_accountTextFiled setInputAccessoryView:self.customTextFieldInputAccessoryView];
        if (@available(iOS 11.0,*)) {
            _accountTextFiled.textContentType =UITextContentTypeUsername;
        }
        [_accountTextFiled setAllCornersWithCornerRadius:6];
        _accountTextFiled.backgroundColor = rgba(247, 248, 250, 1);
        [_accountTextFiled addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
        [_accountTextFiled addTarget:self action:@selector(textEnd:) forControlEvents:UIControlEventEditingDidEnd];
        UIView *leftSpaceView = [[UIView alloc] init];
        leftSpaceView.frame = CGRectMake(0,0,15,49);
        leftSpaceView.backgroundColor = rgba(247, 248, 250, 1);
        
        _accountTextFiled.leftViewMode = UITextFieldViewModeAlways;
        _accountTextFiled.leftView = leftSpaceView;
        
    }

    return _accountTextFiled;
}
-(UITextField *)phoneVeriftyFiled
{
    if (!_phoneVeriftyFiled)
    {
        _phoneVeriftyFiled =[[UITextField alloc] initWithFrame:CGRectMake(32, 6, LTScreenWidth - 64, 49)];
        _phoneVeriftyFiled.font = MFontWithSize(16);
        _phoneVeriftyFiled.textColor = LTTextBlack;
        _phoneVeriftyFiled.clearButtonMode =UITextFieldViewModeWhileEditing;
        _phoneVeriftyFiled.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入验证码" attributes:@{NSFontAttributeName:MFontWithSize(16)}];
        _phoneVeriftyFiled.delegate =self;
        if (@available(iOS 11.0,*)) {
            _phoneVeriftyFiled.textContentType =UITextContentTypeUsername;
        }
        [_phoneVeriftyFiled setAllCornersWithCornerRadius:6];
        _phoneVeriftyFiled.backgroundColor = rgba(247, 248, 250, 1);
        [_phoneVeriftyFiled addTarget:self action:@selector(textEnd:) forControlEvents:UIControlEventEditingDidEnd];
        [_phoneVeriftyFiled addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
        UIView *leftSpaceView = [[UIView alloc] init];
        leftSpaceView.frame = CGRectMake(0,0,15,49);
        leftSpaceView.backgroundColor =rgba(245, 245, 245, 1);
        _phoneVeriftyFiled.leftViewMode = UITextFieldViewModeAlways;
        _phoneVeriftyFiled.leftView = leftSpaceView;
        
        UIView *rightSpaceView = [[UIView alloc] init];
        rightSpaceView.frame = CGRectMake(0,0,100,49);
        [rightSpaceView addSubview:self.sendCodeBtn];
        _phoneVeriftyFiled.rightViewMode = UITextFieldViewModeAlways;
        _phoneVeriftyFiled.rightView = rightSpaceView;
       
    }

    return _phoneVeriftyFiled;
}
- (UIButton *)sendCodeBtn
{
    if (!_sendCodeBtn) {
        _sendCodeBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        _sendCodeBtn.titleLabel.font = RFontWithSize(16);
        [_sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_sendCodeBtn setTitleColor:rgba(41, 121, 255, 1) forState:UIControlStateNormal];
        [_sendCodeBtn setTitleColor:rgba(181, 181, 181, 1) forState:UIControlStateDisabled];
        [_sendCodeBtn addTarget:self action:@selector(sendCodeBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_sendCodeBtn setFrame:CGRectMake(1, 0, 100, 49)];
    }
    
    return _sendCodeBtn;
}
-(NSTimer *)captchaTimer
{
    if (!_captchaTimer)
    {
        _captchaTimer =[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(oneMinutCutdown:) userInfo:nil repeats:YES];
    }
    
    return _captchaTimer;
}

@end
